using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows;
using System.Net.Http;
using WPF_MVVM_Test.MVVM_Model.WorkOrderTask;
using WPF_MVVM_Test.MVVM_ViewModel;
using WPF_MVVM_Test.Services;

namespace WPF_MVVM_Test.MVVM_ViewModel.WorkOrderTask
{
    /// <summary>
    /// 工单任务页面ViewModel
    /// </summary>
    public class WorkOrderTaskViewModel : INotifyPropertyChanged
    {
        #region 私有字段

        private readonly WorkOrderTaskService _workOrderTaskService;
        private readonly SignalRService _signalRService;
        private ObservableCollection<WorkOrderTaskModel> _workOrderTasks = new ObservableCollection<WorkOrderTaskModel>();
        private ObservableCollection<WorkOrderTaskModel> _filteredTasks = new ObservableCollection<WorkOrderTaskModel>();
        private WorkOrderTaskModel _selectedTask;
        private string _searchText;
        private string _selectedStatus;
        private string _selectedStation;
        private DateTime? _startDate;
        private DateTime? _endDate;
        private bool _isLoading;
        private int _currentPage;
        private int _pageSize;
        private int _totalPages;
        private int _totalCount;
        private bool _isAllSelected;

        #endregion

        #region 测试数据方法

        /// <summary>
        /// 加载测试数据确保列表能显示
        /// </summary>
        private void LoadTestData()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("开始加载测试数据...");

                // 清空现有数据
                WorkOrderTasks.Clear();
                FilteredTasks.Clear();

                // 添加测试数据
                for (int i = 1; i <= 5; i++)
                {
                    var testTask = new WorkOrderTaskModel
                    {
                        Id = $"test-{i}",
                        TaskNumber = $"TEST-{i:D3}",
                        TaskName = $"测试任务{i}",
                        StationName = $"测试工作站{i}",
                        Status = i % 2 == 0 ? "进行中" : "未派工",
                        PlanDuration = "8小时",
                        ActualDuration = "0小时",
                        Remarks = $"这是测试任务{i}的备注",
                        ProcessCode = $"P{i:D3}",
                        ProcessName = $"测试工序{i}"
                    };

                    WorkOrderTasks.Add(testTask);
                    FilteredTasks.Add(testTask);
                }

                // 更新计数
                TotalCount = 5;
                TotalPages = 1;

                System.Diagnostics.Debug.WriteLine($"测试数据加载完成，共{FilteredTasks.Count}条记录");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载测试数据失败: {ex.Message}");
            }
        }

        #endregion

        #region 构造函数

        public WorkOrderTaskViewModel()
        {
            System.Diagnostics.Debug.WriteLine("开始初始化WorkOrderTaskViewModel...");

            // 基本初始化
            _workOrderTaskService = new WorkOrderTaskService();
            _signalRService = new SignalRService("http://8.140.242.140:8888/workOrderHub");
            _selectedTask = new WorkOrderTaskModel();
            _searchText = "";
            _selectedStatus = "全部";
            _selectedStation = "全部";

            // 初始化分页
            CurrentPage = 1;
            PageSize = 100;
            TotalCount = 0;
            TotalPages = 1;

            // 初始化下拉选项
            StatusOptions = new ObservableCollection<string> { "全部", "未派工", "已派工", "进行中", "已完成", "已暂停" };
            StationOptions = new ObservableCollection<string> { "全部", "工作站1", "工作站2", "工作站3", "工作站4", "工作站5" };

            // 初始化命令
            InitializeCommands();

            System.Diagnostics.Debug.WriteLine("基本初始化完成，准备加载真实数据...");

            // 延迟加载真实数据，避免构造函数中的异步调用问题
            System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
                new System.Action(async () =>
                {
                    System.Diagnostics.Debug.WriteLine("开始自动加载真实数据...");
                    await LoadDataAsync();
                }),
                System.Windows.Threading.DispatcherPriority.Loaded);

            System.Diagnostics.Debug.WriteLine("WorkOrderTaskViewModel初始化完成");
        }

        #endregion

        #region 公共属性

        /// <summary>
        /// 工单任务集合
        /// </summary>
        public ObservableCollection<WorkOrderTaskModel> WorkOrderTasks
        {
            get
            {
                System.Diagnostics.Debug.WriteLine($"WorkOrderTasks 属性被访问，当前项数: {_workOrderTasks?.Count ?? -1}");
                return _workOrderTasks;
            }
        }

        /// <summary>
        /// 过滤后的任务集合
        /// </summary>
        public ObservableCollection<WorkOrderTaskModel> FilteredTasks
        {
            get
            {
                System.Diagnostics.Debug.WriteLine($"FilteredTasks 属性被访问，当前项数: {_filteredTasks?.Count ?? -1}");
                return _filteredTasks;
            }
            set
            {
                if (_filteredTasks != value)
                {
                    _filteredTasks = value;
                    OnPropertyChanged();
                    System.Diagnostics.Debug.WriteLine($"FilteredTasks 属性被设置，新项数: {_filteredTasks?.Count ?? -1}");
                }
            }
        }

        /// <summary>
        /// 选中的任务
        /// </summary>
        public WorkOrderTaskModel SelectedTask
        {
            get => _selectedTask;
            set => SetProperty(ref _selectedTask, value);
        }

        /// <summary>
        /// 搜索文本
        /// </summary>
        public string SearchText
        {
            get => _searchText;
            set
            {
                if (SetProperty(ref _searchText, value))
                {
                    FilterTasks();
                }
            }
        }

        /// <summary>
        /// 选中的状态
        /// </summary>
        public string SelectedStatus
        {
            get => _selectedStatus;
            set
            {
                if (SetProperty(ref _selectedStatus, value))
                {
                    FilterTasks();
                }
            }
        }

        /// <summary>
        /// 选中的站点
        /// </summary>
        public string SelectedStation
        {
            get => _selectedStation;
            set
            {
                if (SetProperty(ref _selectedStation, value))
                {
                    FilterTasks();
                }
            }
        }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime? StartDate
        {
            get => _startDate;
            set => SetProperty(ref _startDate, value);
        }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime? EndDate
        {
            get => _endDate;
            set => SetProperty(ref _endDate, value);
        }

        /// <summary>
        /// 是否正在加载
        /// </summary>
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        /// <summary>
        /// 状态选项
        /// </summary>
        public ObservableCollection<string> StatusOptions { get; set; }

        /// <summary>
        /// 站点选项
        /// </summary>
        public ObservableCollection<string> StationOptions { get; set; }

        /// <summary>
        /// 是否全选
        /// </summary>
        public bool IsAllSelected
        {
            get => _isAllSelected;
            set
            {
                _isAllSelected = value;
                OnPropertyChanged();

                // 直接更新所有未派工和未开工任务的选择状态
                if (FilteredTasks != null)
                {
                    foreach (var task in FilteredTasks.Where(t => t.Status == "未派工" || t.Status == "未开工"))
                    {
                        task.IsSelected = value;
                    }
                }

                // 更新相关属性
                OnPropertyChanged(nameof(HasSelectedTasks));
                OnPropertyChanged(nameof(SelectedTasksCountText));
            }
        }

        /// <summary>
        /// 是否有选中的任务
        /// </summary>
        public bool HasSelectedTasks => FilteredTasks?.Any(t => t.IsSelected && (t.Status == "未派工" || t.Status == "未开工")) == true;

        /// <summary>
        /// 是否有选中的已完成任务
        /// </summary>
        public bool HasSelectedCompletedTasks => FilteredTasks?.Any(t => t.IsSelected && t.Status == "已完成") == true;

        /// <summary>
        /// 选中任务数量文本
        /// </summary>
        public string SelectedTasksCountText
        {
            get
            {
                var selectedDispatchCount = FilteredTasks?.Count(t => t.IsSelected && (t.Status == "未派工" || t.Status == "未开工")) ?? 0;
                var totalUnassigned = FilteredTasks?.Count(t => t.Status == "未派工" || t.Status == "未开工") ?? 0;
                var selectedReportCount = FilteredTasks?.Count(t => t.IsSelected && t.Status == "已完成") ?? 0;
                var totalCompleted = FilteredTasks?.Count(t => t.Status == "已完成") ?? 0;

                if (selectedDispatchCount > 0 && selectedReportCount > 0)
                {
                    return $"已选择 {selectedDispatchCount} 个可派工任务，{selectedReportCount} 个可报工任务";
                }
                else if (selectedDispatchCount > 0)
                {
                    return $"已选择 {selectedDispatchCount} 个可派工任务，共 {totalUnassigned} 个可派工任务";
                }
                else if (selectedReportCount > 0)
                {
                    return $"已选择 {selectedReportCount} 个可报工任务，共 {totalCompleted} 个可报工任务";
                }
                else
                {
                    return $"共 {totalUnassigned} 个可派工任务，{totalCompleted} 个可报工任务";
                }
            }
        }

        #endregion

        #region 命令

        public ICommand SearchCommand { get; private set; }
        public ICommand ResetCommand { get; private set; }
        public ICommand RefreshCommand { get; private set; }
        public ICommand StartTaskCommand { get; private set; }
        public ICommand CompleteTaskCommand { get; private set; }
        public ICommand PauseTaskCommand { get; private set; }
        public ICommand EditTaskCommand { get; private set; }
        public ICommand StartWorkCommand { get; private set; }
        public ICommand CloseTaskCommand { get; private set; }
        public ICommand ReportWorkCommand { get; private set; }
        public ICommand RestartTaskCommand { get; private set; }
        public ICommand ViewTaskCommand { get; private set; }
        public ICommand FirstPageCommand { get; private set; }
        public ICommand PreviousPageCommand { get; private set; }
        public ICommand NextPageCommand { get; private set; }
        public ICommand LastPageCommand { get; private set; }
        public ICommand SelectAllCommand { get; private set; }
        public ICommand BatchDispatchCommand { get; private set; }
        public ICommand BatchReportCommand { get; private set; }
        public ICommand TaskSelectionChangedCommand { get; private set; }

        #endregion

        #region 私有方法

        private void LoadMockData()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("开始加载模拟数据");

                // 创建模拟数据
                var mockTasks = new List<WorkOrderTaskModel>();
                for (int i = 1; i <= 20; i++)
                {
                    mockTasks.Add(new WorkOrderTaskModel
                    {
                        Id = $"TASK{i:D3}",
                        Index = i,
                        TaskNumber = $"WO2024{i:D4}",
                        TaskName = $"生产任务{i}",
                        StationName = $"工作站{(i % 5) + 1}",
                        ProcessCode = $"P{i:D3}",
                        ProcessName = $"工艺{i}",
                        PlanStartTime = DateTime.Now.AddDays(i - 10),
                        PlanEndTime = DateTime.Now.AddDays(i - 9),
                        PlanQuantity = 100 + (i * 10),
                        ActualQuantity = i <= 10 ? 100 + (i * 10) : 0,
                        Status = i <= 5 ? "已完成" : i <= 10 ? "进行中" : i <= 15 ? "已派工" : "未派工",
                        PlanDuration = "8小时",
                        ActualDuration = i <= 10 ? "7小时30分钟" : "未设置",
                        Remarks = $"备注信息{i}"
                    });
                }

                // 更新UI
                WorkOrderTasks.Clear();
                FilteredTasks.Clear();

                foreach (var task in mockTasks)
                {
                    WorkOrderTasks.Add(task);
                    FilteredTasks.Add(task);
                }

                // 更新分页信息
                TotalCount = mockTasks.Count;
                TotalPages = (int)Math.Ceiling((double)TotalCount / PageSize);

                System.Diagnostics.Debug.WriteLine($"模拟数据加载完成 - 任务数量: {FilteredTasks.Count}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载模拟数据失败: {ex.Message}");
            }
        }

        private async Task TestApiConnectionAsync()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("开始测试API连接...");
                using (var httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri("http://8.140.242.140:8888/");
                    httpClient.Timeout = TimeSpan.FromSeconds(5);

                    var response = await httpClient.GetAsync("api/WorkOrderTask/debug/simple-page?pageIndex=1&pageSize=10");
                    System.Diagnostics.Debug.WriteLine($"API连接测试结果: {response.StatusCode}");

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        System.Diagnostics.Debug.WriteLine($"API响应内容: {content.Substring(0, Math.Min(200, content.Length))}...");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"API连接测试失败: {ex.Message}");

                // 在UI线程上显示错误信息
                Application.Current?.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show($"无法连接到后端API服务 (http://8.140.242.140:8888/)\n\n错误信息: {ex.Message}\n\n请确保后端服务正在运行。",
                        "API连接失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                });
            }
        }

        private void InitializeCommands()
        {
            SearchCommand = new RelayCommand(async () => await SearchAsync());
            ResetCommand = new RelayCommand(ResetSearch);
            RefreshCommand = new RelayCommand(async () => await LoadDataAsync());
            StartTaskCommand = new RelayCommand<WorkOrderTaskModel>(async task => await StartTaskAsync(task));
            CompleteTaskCommand = new RelayCommand<WorkOrderTaskModel>(async task => await CompleteTaskAsync(task));
            PauseTaskCommand = new RelayCommand<WorkOrderTaskModel>(async task => await PauseTaskAsync(task));
            EditTaskCommand = new RelayCommand<WorkOrderTaskModel>(async task => await EditTaskAsync(task));
            StartWorkCommand = new RelayCommand<WorkOrderTaskModel>(async task => await StartWorkAsync(task));
            CloseTaskCommand = new RelayCommand<WorkOrderTaskModel>(async task => await CloseTaskAsync(task));
            ReportWorkCommand = new RelayCommand<WorkOrderTaskModel>(async task => await ReportWorkAsync(task));
            RestartTaskCommand = new RelayCommand<WorkOrderTaskModel>(async task => await RestartTaskAsync(task));
            ViewTaskCommand = new RelayCommand<WorkOrderTaskModel>(async task => await ViewTaskAsync(task));
            FirstPageCommand = new RelayCommand(GoToFirstPage, () => CurrentPage > 1);
            PreviousPageCommand = new RelayCommand(GoToPreviousPage, () => CurrentPage > 1);
            NextPageCommand = new RelayCommand(GoToNextPage, () => CurrentPage < TotalPages);
            LastPageCommand = new RelayCommand(GoToLastPage, () => CurrentPage < TotalPages);
            SelectAllCommand = new RelayCommand(ToggleSelectAll);
            BatchDispatchCommand = new RelayCommand(async () => await BatchDispatchAsync(), () => HasSelectedTasks);
            BatchReportCommand = new RelayCommand(async () => await BatchReportAsync(), () => HasSelectedCompletedTasks);
            TaskSelectionChangedCommand = new RelayCommand<WorkOrderTaskModel>(OnTaskSelectionChanged);
        }

        private async Task LoadDataAsync()
        {
            try
            {
                IsLoading = true;
                System.Diagnostics.Debug.WriteLine($"开始加载数据 - 页码: {CurrentPage}, 页大小: {PageSize}");

                // 使用新的API方法获取分页数据
                var (tasks, totalCount) = await _workOrderTaskService.GetWorkOrderTasksAsync(CurrentPage, PageSize);

                System.Diagnostics.Debug.WriteLine($"API返回数据 - 任务数量: {tasks?.Count ?? 0}, 总数量: {totalCount}");

                // 确保在UI线程上更新数据
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    System.Diagnostics.Debug.WriteLine($"UI线程开始更新数据");
                    System.Diagnostics.Debug.WriteLine($"tasks是否为null: {tasks == null}");
                    System.Diagnostics.Debug.WriteLine($"tasks数量: {tasks?.Count ?? -1}");

                    if (tasks != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"开始处理{tasks.Count}个任务");

                        // 清空并重新填充WorkOrderTasks
                        System.Diagnostics.Debug.WriteLine($"清空WorkOrderTasks，当前数量: {WorkOrderTasks.Count}");
                        WorkOrderTasks.Clear();
                        System.Diagnostics.Debug.WriteLine($"WorkOrderTasks清空完成，当前数量: {WorkOrderTasks.Count}");

                        // 清空并重新填充FilteredTasks
                        System.Diagnostics.Debug.WriteLine($"清空FilteredTasks，当前数量: {FilteredTasks.Count}");
                        FilteredTasks.Clear();
                        System.Diagnostics.Debug.WriteLine($"FilteredTasks清空完成，当前数量: {FilteredTasks.Count}");

                        if (tasks.Count > 0)
                        {
                            foreach (var task in tasks)
                            {
                                System.Diagnostics.Debug.WriteLine($"添加任务: {task?.TaskNumber} - {task?.TaskName}");
                                WorkOrderTasks.Add(task);
                                FilteredTasks.Add(task);
                            }
                            System.Diagnostics.Debug.WriteLine($"所有任务添加完成 - WorkOrderTasks: {WorkOrderTasks.Count}, FilteredTasks: {FilteredTasks.Count}");

                            // 更新分页信息
                            TotalCount = totalCount;
                            TotalPages = totalCount > 0 ? (int)Math.Ceiling((double)TotalCount / PageSize) : 1;
                            System.Diagnostics.Debug.WriteLine($"分页信息更新 - 总数: {TotalCount}, 总页数: {TotalPages}");

                            // 重置选择状态
                            ResetSelectionState();

                            // 强制触发PropertyChanged事件
                            OnPropertyChanged(nameof(WorkOrderTasks));
                            OnPropertyChanged(nameof(FilteredTasks));
                            OnPropertyChanged(nameof(TotalCount));
                            OnPropertyChanged(nameof(TotalPages));
                            System.Diagnostics.Debug.WriteLine("PropertyChanged事件已触发");
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("API返回空列表，保持现有测试数据");
                            // 如果API返回空数据，但当前没有任何数据，则添加测试数据
                            if (WorkOrderTasks.Count == 0)
                            {
                                AddTestData();
                            }
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("API返回null，保持现有测试数据");
                        // 如果API返回null，但当前没有任何数据，则添加测试数据
                        if (WorkOrderTasks.Count == 0)
                        {
                            AddTestData();
                        }
                    }
                    System.Diagnostics.Debug.WriteLine($"UI线程数据更新完成 - 最终数量 WorkOrderTasks: {WorkOrderTasks.Count}, FilteredTasks: {FilteredTasks.Count}");
                });

                System.Diagnostics.Debug.WriteLine($"数据加载完成 - 显示任务数量: {FilteredTasks.Count}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载数据失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常详情: {ex}");

                // API调用失败时，保持现有数据或添加测试数据
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    if (WorkOrderTasks.Count == 0)
                    {
                        System.Diagnostics.Debug.WriteLine("API调用失败且无现有数据，添加测试数据");
                        AddTestData();
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("API调用失败，保持现有数据");
                    }

                    // 显示错误信息（可选，避免频繁弹窗）
                    // MessageBox.Show($"加载数据失败: {ex.Message}\n\n当前显示测试数据。",
                    //     "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                });
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void AddTestData()
        {
            System.Diagnostics.Debug.WriteLine("开始添加测试数据...");

            var testTask = new WorkOrderTaskModel
            {
                Id = "1",
                TaskNumber = "T001",
                TaskName = "测试任务1",
                StationName = "工作站1",
                Status = "进行中",
                PlanDuration = "8小时",
                ActualDuration = "2小时",
                Remarks = "测试备注",
                ProcessCode = "P001",
                ProcessName = "测试工序"
            };

            WorkOrderTasks.Clear();
            FilteredTasks.Clear();

            WorkOrderTasks.Add(testTask);
            FilteredTasks.Add(testTask);

            TotalCount = 1;
            TotalPages = 1;

            System.Diagnostics.Debug.WriteLine($"测试数据添加完成！WorkOrderTasks: {WorkOrderTasks.Count}, FilteredTasks: {FilteredTasks.Count}");
        }

        private async Task SearchAsync()
        {
            try
            {
                IsLoading = true;

                // 重新加载当前页的数据
                // 注意：这里简化处理，实际应该将搜索条件传递给API
                var (tasks, totalCount) = await _workOrderTaskService.GetWorkOrderTasksAsync(CurrentPage, PageSize);

                // 本地过滤（临时方案，理想情况下应该在API端处理）
                var filteredTasks = tasks.AsEnumerable();

                if (!string.IsNullOrEmpty(SearchText))
                {
                    filteredTasks = filteredTasks.Where(t =>
                        t.TaskName?.Contains(SearchText, StringComparison.OrdinalIgnoreCase) == true ||
                        t.TaskNumber?.Contains(SearchText, StringComparison.OrdinalIgnoreCase) == true);
                }

                if (!string.IsNullOrEmpty(SelectedStatus) && SelectedStatus != "全部")
                {
                    filteredTasks = filteredTasks.Where(t => t.Status == SelectedStatus);
                }

                if (!string.IsNullOrEmpty(SelectedStation) && SelectedStation != "全部")
                {
                    filteredTasks = filteredTasks.Where(t => t.StationName == SelectedStation);
                }

                if (StartDate.HasValue)
                {
                    filteredTasks = filteredTasks.Where(t => t.PlanStartTime >= StartDate.Value);
                }

                if (EndDate.HasValue)
                {
                    filteredTasks = filteredTasks.Where(t => t.PlanStartTime <= EndDate.Value);
                }

                var resultTasks = filteredTasks.ToList();

                // 在UI线程上更新结果
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _filteredTasks.Clear();
                    foreach (var task in resultTasks)
                    {
                        _filteredTasks.Add(task);
                    }

                    // 重置选择状态
                    ResetSelectionState();

                    // 更新分页信息（基于过滤后的结果）
                    TotalCount = resultTasks.Count;
                    TotalPages = Math.Max(1, (int)Math.Ceiling((double)TotalCount / PageSize));
                });

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"搜索失败: {ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void FilterTasks()
        {
            _ = SearchAsync();
        }

        private void ResetSearch()
        {
            SearchText = string.Empty;
            SelectedStatus = "全部";
            SelectedStation = "全部";
            StartDate = null;
            EndDate = null;
            CurrentPage = 1;
            _ = SearchAsync();
        }

        private async Task StartTaskAsync(WorkOrderTaskModel task)
        {
            if (task != null && (task.Status == "未派工" || task.Status == "未开工"))
            {
                try
                {
                    var dialog = new MVVM_View.WorkOrderTask.WorkOrderTaskEditDialog(task, false);
                    var result = dialog.ShowDialog();

                    if (result == true && dialog.IsConfirmed)
                    {
                        // 派工成功，刷新数据
                        await SearchAsync();
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"打开派工对话框失败: {ex.Message}");
                }
            }
        }

        private async Task CompleteTaskAsync(WorkOrderTaskModel task)
        {
            if (task != null && task.Status == "进行中")
            {
                try
                {
                    // 直接在前台更新状态，不调用后台接口
                    task.Status = "已完成";
                    task.ActualEndTime = DateTime.Now;

                    // 显示成功消息
                    System.Windows.MessageBox.Show($"任务 {task.TaskNumber} 已完工！现在可以进行报工操作。", "完工成功",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show($"完工失败: {ex.Message}", "错误",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            else
            {
                System.Windows.MessageBox.Show("只有进行中状态的任务才能完工！", "提示",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            }
        }

        private async Task PauseTaskAsync(WorkOrderTaskModel task)
        {
            if (task != null)
            {
                var success = await _workOrderTaskService.PauseTaskAsync(task.Id);
                if (success)
                {
                    task.Status = "已暂停";
                }
            }
        }

        private async Task EditTaskAsync(WorkOrderTaskModel task)
        {
            if (task != null)
            {
                try
                {
                    var dialog = new MVVM_View.WorkOrderTask.WorkOrderTaskEditDialog(task, true);
                    var result = dialog.ShowDialog();

                    if (result == true && dialog.IsConfirmed)
                    {
                        // 编辑成功，刷新数据
                        await SearchAsync();
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"打开编辑对话框失败: {ex.Message}");
                }
            }
        }

        private async Task StartWorkAsync(WorkOrderTaskModel task)
        {
            if (task != null && (task.Status == "已下达" || task.Status == "已派工"))
            {
                try
                {
                    // 直接在前台更新状态，不调用后台接口
                    task.Status = "进行中";
                    task.ActualStartTime = DateTime.Now;

                    // 显示成功消息
                    System.Windows.MessageBox.Show($"任务 {task.TaskNumber} 已开工！", "开工成功",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show($"开工失败: {ex.Message}", "错误",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            else
            {
                System.Windows.MessageBox.Show("只有已下达或已派工状态的任务才能开工！", "提示",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            }
        }

        private async Task CloseTaskAsync(WorkOrderTaskModel task)
        {
            if (task != null)
            {
                var success = await _workOrderTaskService.UpdateTaskStatusAsync(task.Id, "已关闭");
                if (success)
                {
                    task.Status = "已关闭";
                }
            }
        }

        private async Task ReportWorkAsync(WorkOrderTaskModel task)
        {
            if (task != null && task.Status == "已完成")
            {
                try
                {
                    // 打开报工对话框
                    var dialog = new WPF_MVVM_Test.MVVM_View.WorkOrderTask.WorkReportDialog(task);
                    var result = dialog.ShowDialog();

                    if (result == true)
                    {
                        // 获取用户输入的报工数据
                        var reportRequest = dialog.GetWorkReportRequest();

                        // 调用后台API进行报工
                        var success = await _workOrderTaskService.SubmitWorkReportAsync(task, reportRequest);

                        if (success)
                        {
                            // 报工成功，更新任务状态为已报工
                            task.Status = "已报工";
                            task.ActualEndTime = DateTime.Now;

                            System.Diagnostics.Debug.WriteLine($"报工成功: {task.TaskName}");
                            System.Windows.MessageBox.Show($"任务 {task.TaskNumber} 报工成功！", "报工成功",
                                System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                        }
                        else
                        {
                            System.Windows.MessageBox.Show($"任务 {task.TaskNumber} 报工失败，请重试！", "报工失败",
                                System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"报工异常: {ex.Message}");
                    System.Windows.MessageBox.Show($"报工异常: {ex.Message}", "错误",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            else
            {
                System.Windows.MessageBox.Show("只有已完成状态的任务才能报工！", "提示",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            }
        }

        private async Task RestartTaskAsync(WorkOrderTaskModel task)
        {
            if (task != null && (task.Status == "已完成" || task.Status == "已关闭"))
            {
                var success = await _workOrderTaskService.UpdateTaskStatusAsync(task.Id, "未派工");
                if (success)
                {
                    task.Status = "未派工";
                    task.ActualStartTime = null;
                    task.ActualEndTime = null;
                }
            }
        }

        private async Task ViewTaskAsync(WorkOrderTaskModel task)
        {
            if (task != null)
            {
                // 这里应该打开查看详情对话框
                // 目前只是模拟操作
                await Task.Delay(100);
                System.Diagnostics.Debug.WriteLine($"查看任务详情: {task.TaskName}");
            }
        }

        #endregion

        #region 分页方法

        private void GoToFirstPage()
        {
            CurrentPage = 1;
            _ = SearchAsync();
        }

        private void GoToPreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                _ = SearchAsync();
            }
        }

        private void GoToNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                _ = SearchAsync();
            }
        }

        private void GoToLastPage()
        {
            CurrentPage = TotalPages;
            _ = SearchAsync();
        }

        #endregion

        #region 批量派工相关方法

        /// <summary>
        /// 更新所有任务的选中状态
        /// </summary>
        private void UpdateAllTasksSelection(bool isSelected)
        {
            if (FilteredTasks == null) return;

            foreach (var task in FilteredTasks.Where(t => t.Status == "未派工" || t.Status == "未开工"))
            {
                task.IsSelected = isSelected;
            }
        }

        /// <summary>
        /// 切换全选状态
        /// </summary>
        private void ToggleSelectAll()
        {
            IsAllSelected = !IsAllSelected;
        }

        /// <summary>
        /// 批量派工
        /// </summary>
        private async Task BatchDispatchAsync()
        {
            // 获取选中的未派工或未开工任务
            var selectedTasks = FilteredTasks?.Where(t => t.IsSelected && (t.Status == "未派工" || t.Status == "未开工")).ToList();

            if (selectedTasks == null || selectedTasks.Count == 0)
            {
                System.Windows.MessageBox.Show("请选择要派工的任务！", "提示",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                return;
            }

            // 显示派工对话框
            var dialog = new WPF_MVVM_Test.MVVM_View.WorkOrderTask.DispatchDialog(selectedTasks);
            if (dialog.ShowDialog() == true)
            {
                // 派工成功后，更新任务状态并刷新界面
                foreach (var task in selectedTasks)
                {
                    task.Status = "已派工";
                    task.IsSelected = false;
                }

                // 刷新界面
                OnPropertyChanged(nameof(FilteredTasks));
                OnPropertyChanged(nameof(HasSelectedTasks));
                OnPropertyChanged(nameof(SelectedTasksCountText));
                OnPropertyChanged(nameof(IsAllSelected));

                System.Windows.MessageBox.Show($"成功派工 {selectedTasks.Count} 个任务！", "成功",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
            }
        }

        /// <summary>
        /// 批量报工
        /// </summary>
        private async Task BatchReportAsync()
        {
            // 获取选中的已完成任务
            var selectedTasks = FilteredTasks?.Where(t => t.IsSelected && t.Status == "已完成").ToList();

            if (selectedTasks == null || selectedTasks.Count == 0)
            {
                System.Windows.MessageBox.Show("请选择要报工的已完成任务！", "提示",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                return;
            }

            var result = System.Windows.MessageBox.Show($"确定要对选中的 {selectedTasks.Count} 个已完成任务进行批量报工吗？", "确认批量报工",
                System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);

            if (result == System.Windows.MessageBoxResult.Yes)
            {
                try
                {
                    // 创建批量报工请求数据
                    var reportRequests = selectedTasks.Select(task =>
                        _workOrderTaskService.CreateWorkReportRequest(task, 1, 0, 0, 0, "合格")).ToList();

                    // 调用批量报工API
                    var success = await _workOrderTaskService.SubmitBatchWorkReportAsync(reportRequests);

                    if (success)
                    {
                        // 批量报工成功，更新任务状态为已报工
                        foreach (var task in selectedTasks)
                        {
                            task.Status = "已报工";
                            task.ActualEndTime = DateTime.Now;
                            task.IsSelected = false; // 取消选择
                        }

                        // 更新相关属性
                        OnPropertyChanged(nameof(HasSelectedTasks));
                        OnPropertyChanged(nameof(HasSelectedCompletedTasks));
                        OnPropertyChanged(nameof(SelectedTasksCountText));
                        OnPropertyChanged(nameof(IsAllSelected));

                        System.Windows.MessageBox.Show($"成功报工 {selectedTasks.Count} 个任务！", "成功",
                            System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("批量报工失败，请重试！", "失败",
                            System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show($"批量报工异常: {ex.Message}", "错误",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 任务选择状态改变时的处理
        /// </summary>
        public void OnTaskSelectionChanged(WorkOrderTaskModel task)
        {
            // 更新相关属性
            OnPropertyChanged(nameof(HasSelectedTasks));
            OnPropertyChanged(nameof(HasSelectedCompletedTasks));
            OnPropertyChanged(nameof(SelectedTasksCountText));

            // 检查是否所有未派工和未开工任务都被选中
            var unassignedTasks = FilteredTasks?.Where(t => t.Status == "未派工" || t.Status == "未开工").ToList();
            if (unassignedTasks != null && unassignedTasks.Any())
            {
                _isAllSelected = unassignedTasks.All(t => t.IsSelected);
                OnPropertyChanged(nameof(IsAllSelected));
            }
        }

        /// <summary>
        /// 重置选择状态
        /// </summary>
        private void ResetSelectionState()
        {
            // 清除所有任务的选择状态
            if (FilteredTasks != null)
            {
                foreach (var task in FilteredTasks)
                {
                    task.IsSelected = false;
                }
            }

            // 重置全选状态
            _isAllSelected = false;
            OnPropertyChanged(nameof(IsAllSelected));
            OnPropertyChanged(nameof(HasSelectedTasks));
            OnPropertyChanged(nameof(SelectedTasksCountText));
        }



        #endregion

        #region INotifyPropertyChanged实现

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
        {
            if (Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        #endregion

        #region SignalR相关方法

        /// <summary>
        /// 初始化SignalR连接
        /// </summary>
        private async Task InitializeSignalRAsync()
        {
            try
            {
                _signalRService.NotificationReceived += OnWorkOrderUpdatedFromSignalR;
                var connected = await _signalRService.ConnectAsync();
                if (!connected)
                {
                    System.Diagnostics.Debug.WriteLine("SignalR连接失败，将使用轮询模式");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"初始化SignalR时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理SignalR工单更新消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="message"></param>
        private void OnWorkOrderUpdatedFromSignalR(object sender, string message)
        {
            try
            {
                // 在UI线程上执行
                Application.Current?.Dispatcher.Invoke(async () =>
                {
                    System.Diagnostics.Debug.WriteLine($"收到SignalR消息: {message}");
                    // 刷新数据
                    await LoadDataAsync();
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理SignalR消息时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            try
            {
                _signalRService?.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"释放SignalR资源时出错: {ex.Message}");
            }
        }

        #endregion
    }
}
